package com.alex.springboot.dao.impl;

import com.alex.springboot.dao.UserDAO;
import com.alex.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(User user) {
        return jdbcTemplate.update("insert into t_user(name,money) values(?,?)", user.getName(), user.getMoney());
    }

    @Override
    public int delete(Integer id) {
        return jdbcTemplate.update("delete from t_user where id=?", id);
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update("update t_user set name=?,money=? where id=?", user.getName(), user.getMoney(), user.getId());
    }

    @Override
    public User getById(Integer id) {
        return jdbcTemplate.queryForObject("select id,name,money from t_user where id=?", new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public List<User> selectAll() {
        return jdbcTemplate.query("select id,name,money from t_user", new BeanPropertyRowMapper<>(User.class));
    }
}
